import PocketBase from "../js/pocketbase.es.js";
import dayjs from "../js/dayjs.min.js";
const html = String.raw;

export function renderUsers(data = []) {
  return html`
    <div style="margin:10px">
      <div class="form-check form-check-inline">
        <input
          class="form-check-input"
          type="checkbox"
          name="name"
          checked
          data-action="changeHeader"
        />
        <label class="form-check-label">姓名</label>
      </div>
      <div class="form-check form-check-inline">
        <input
          class="form-check-input"
          type="checkbox"
          name="age"
          checked
          data-action="changeHeader"
        />
        <label class="form-check-label">年龄</label>
      </div>
    </div>

    <table class="table">
      <thead>
        <tr>
          <th data-field="name">姓名</th>
          <th data-field="age">年龄</th>
          <th>邮箱</th>
          <th>手机</th>
          <th>性别</th>
          <th>部门</th>
          <th>创建时间</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        ${data
          .map(
            (el) => html`<tr>
              <td data-field="name">${el.name}</td>
              <td data-field="age">${el.age}</td>
              <td>${el.email}</td>
              <td>${el.phone}</td>
              <td>${el.gender === "1" ? "男" : "女"}</td>
              <td>
                ${el.expand && el.expand.department
                  ? el.expand.department.label
                  : "无"}
              </td>
              <td>${dayjs(el.created).format("YYYY-MM-DD HH:mm:ss")}</td>
              <td>
                <button class="btn btn-primary" data-action="editUser">
                  <i class="fa-solid fa-pen-to-square"></i> 编辑
                </button>
                <button
                  class="btn btn-danger"
                  data-action="deleteUser"
                  data-id="${el.id}"
                >
                  <i class="fa-solid fa-trash-can"></i> 删除
                </button>
              </td>
            </tr>`
          )
          .join("")}
      </tbody>
    </table>
  `;
}

export function renderPagination(totalPages = 0, page = 1) {
  const pagesArr = Array.from({ length: totalPages }, (el, i) => i + 1);
  return html` <ul class="pagination">
    <li class="page-item ${page === 1 ? "disabled" : ""}">
      <a class="page-link" href="#" data-action="toPage" data-page="${page - 1}"
        >上一页</a
      >
    </li>
    ${pagesArr
      .map(
        (el) =>
          html`<li class="page-item ${page === el ? "active" : ""}">
            <a class="page-link" href="#" data-action="toPage" data-page="${el}"
              >${el}</a
            >
          </li>`
      )
      .join("")}
    <li class="page-item ${page === totalPages ? "disabled" : ""}">
      <a class="page-link" href="#" data-action="toPage" data-page="${page + 1}"
        >下一页</a
      >
    </li>
  </ul>`;
}

export async function getUsers(page = 1, filter = "") {
  const pb = new PocketBase("http://127.0.0.1:8090");
  const resultList = await pb.collection("users").getList(page, 1, {
    filter,
    expand: "department",
  });
  // 生成用户表
  document.getElementById("usersBox").innerHTML = renderUsers(resultList.items);
  // 生成分页
  document.getElementById("usersPagination").innerHTML = renderPagination(
    resultList.totalPages,
    resultList.page
  );
}

export function on(ename, methods, action = "action") {
  document.addEventListener(ename, function (e) {
    const act = e.target.dataset[action];
    if (act === undefined) return;
    if (methods[act] === undefined) return;
    e.preventDefault();
    methods[act].call(e.target);
  });
}

export async function deleteUserApi(id) {
  const pb = new PocketBase("http://127.0.0.1:8090");
  await pb.collection("users").delete(id);
  getUsers();
}

export async function updateUserApi(id, data) {
  const pb = new PocketBase("http://127.0.0.1:8090");
  const record = await pb.collection("users").update(id, data);
}

export async function createUserApi(data) {
  const pb = new PocketBase("http://127.0.0.1:8090");
  try {
    await pb.collection("users").create({
      emailVisibility: true,
      ...data,
      age: 20,
    });
    location.href = "./users.html";
  } catch (error) {
    console.dir(error);
  }
}
